package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备信息Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-05
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    //注入华为云
    @Autowired
    private IoTDAClient ioTDAClient;

    //注入redis缓存
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备信息
     * 
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备信息列表
     * 
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     * 
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备信息
     * 
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备信息
     * 
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息信息
     * 
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = ioTDAClient.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表失败");
        }

        //保存产品到redis
        List<ProductSummary> products = response.getProducts();
        if (CollectionUtil.isEmpty(products)) {
            //警告
            log.warn("iot平台没有产品");
            return;
        }
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
    }

    /**
     * 查询所有产品
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String products = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        if (StringUtils.isEmpty(products)) {
            return Collections.emptyList();
        }
        //反序列化为json
        return JSONUtil.toList(products, ProductVo.class);

    }

    /**
     * 注册设备
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {

        //1.设备名称是否重复, 如果重复，则提示设备名称重复
        Long countName = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName())
                .count();
        if (countName > 0) {
            throw new BaseException("设备名称重复");
        }
        //2.设备标识是否重复
        Long countNode = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId())
                .count();
        if (countNode > 0) {
            throw new BaseException("设备标识重复");
        }

        //2.1判断如果是随身设备，将物理位置设为-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //3.同一位置是否满足绑定了相同的产品
        Long countSame = lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (countSame > 0) {
            throw new BaseException("同一位置绑定了相同的产品");
        }

        //4.注册设备到华为IOT云
        //4.1随机生成密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");

        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        //使用链式编程
        addDevice.withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.productKey)
                .withNodeId(deviceDto.getNodeId())
                .withAuthInfo(new AuthInfo().withSecret(secret));
        addDeviceRequest.withBody(addDevice);
        AddDeviceResponse response = null;
        try {
            response = ioTDAClient.addDevice(addDeviceRequest);
        } catch (Exception e) {
            log.error("注册设备失败", e);
            throw new BaseException("注册设备失败");
        }

        //5.本地保存设备
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        save(device);
    }

    /**
     * 查看设备详情
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo showDeviceDetail(String iotId) {
        //1.查询数据库 iotId
        Device device = lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();
        //判断数据是否为空
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }


        //2.调用华为云IOT接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = null;
        try{
            response = ioTDAClient.showDevice(request);
        } catch (Exception e) {
            log.error("查询设备详情失败", e);
            throw new BaseException("查询设备详情失败");
        }

        //3.封装到VO返回
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);

        //4.获取设备状态
        String status = response.getStatus();

        //5.获取设备激活时间
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTime)) {
            //转换为LocalDateTime
            LocalDateTime parsedTime = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            //日期时区转换 GMT+0 UTC GMT+8 CST
            LocalDateTime localDateTime = parsedTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(localDateTime);
        }
        vo.setDeviceStatus(status);

        return vo;
    }

    /**
     * 修改设备信息
     * @param deviceDto
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {
        //1.修改本地数据
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        updateById(device);
        //相同的位置不能修改
        Long countSame = lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .ne(Device::getId, device.getId())
                .count();
                if (countSame > 0) {
                    throw new BaseException("同一位置已绑定了相同的产品,无法修改,请重新操作!");
                }

        // 2.修改IOT数据
        UpdateDeviceRequest updateDeviceRequest = new UpdateDeviceRequest();
        UpdateDevice updateDevice = new UpdateDevice();

        // 设置设备基本信息（如设备名称、产品ID等）
        //  设置设备ID
        updateDeviceRequest.withDeviceId(deviceDto.getIotId());
        //  设置设备基本信息
        updateDeviceRequest.withBody(updateDevice);
        //  设置设备名称
        updateDevice.withDeviceName(deviceDto.getDeviceName());
        // 创建一个空的响应对象,  用于存储响应结果
        UpdateDeviceResponse updateDeviceResponse;
       //判断响应结果
        try {
           updateDeviceResponse = ioTDAClient.updateDevice(updateDeviceRequest);
        } catch (Exception e) {
            log.error("更新物联网设备失败", e);
            throw new BaseException("更新物联网设备失败");
        }
    }

    /**
     * 删除设备
     * @param iotId
     */
    @Override
    @Transactional
    public void deleteDeviceById(String iotId) {
        //获取iot删除请求
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.withDeviceId(iotId);
        //调用华为云删除接口
        try {
            ioTDAClient.deleteDevice(deleteDeviceRequest);
        } catch (Exception e) {
            log.error("调用华为云删除设备接口失败", e);
            throw new BaseException("删除物联网设备失败：" + e.getMessage());
        }

        // 需要同步删除本地数据库记录
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device != null) {
            removeById(device.getId());
        }

    }

    /**
     * 查询设备影子数据
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //1.调用华为云IOT平台获取数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        //设置设备ID
        request.setDeviceId(iotId);
        //获取响应数据
        ShowDeviceShadowResponse response;
        try {
            response = ioTDAClient.showDeviceShadow(request);
        } catch (Exception e) {
            log.error("查询影子数据失败", e);
            throw new BaseException("查询影子数据失败");
        }
        //2.解析数据 对象[{a,b,c}]
        //从响应体中拿到影子数据
        List<DeviceShadowData> shadow = response.getShadow();
        //判断是否为空
        if (CollUtil.isEmpty(shadow)) {
            return Collections.emptyList();
        }

        //获取到reported中数据
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();
        //判断空值
        if (ObjectUtil.isNull(reported)) {
            return Collections.emptyList();
        }

        //获取上报时间eventTime
        String eventTime = reported.getEventTime();
            //解析时间
        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime localDateTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //获取属性properties ->jsonObject
        Object properties = reported.getProperties();
        //转为jsonObject
        JSONObject jsonObject = JSONUtil.parseObj(properties);
        //遍历
        List<Map<String, Object>> list = new ArrayList<>();
        jsonObject.forEach((k,v) -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("eventTime", localDateTime);
            map.put("value", v);
            //添加到List
            list.add(map);
        });

        return list;
    }

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = ioTDAClient.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
